using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.IO;

/// <summary>
/// Summary description for AsymetricEncryptor
/// </summary>
public static class AsymetricEncryptor
{
    private static bool ReadKey(string publicKeyFilePath, out string keyString, out string exeptionString)
    {
        byte[] keyBytes;
        exeptionString = "";
        keyString = "";

        try
        {
            using (FileStream fs = new FileStream(publicKeyFilePath, FileMode.Open))
            {
                keyBytes = new byte[fs.Length];
                fs.Read(keyBytes, 0, (int)fs.Length);
                keyString = Encoding.UTF8.GetString(keyBytes);
            }
        }
        catch (FileNotFoundException ex)
        {
            exeptionString = ex.Message;
            return false;
        }
        catch (FileLoadException ex)
        {
            exeptionString = ex.Message;
            return false;
        }
        catch (Exception ex)
        {
            exeptionString = ex.Message;
            return false;
        }
        return true;
    }

    public static bool EncryptData(string data, string publicKeyFilePath, out byte[] encryptedData, out string exeptionString)
    {
        string readKeyExeption;
        string publicKey;
        exeptionString = "";
        encryptedData = null;

        if (!ReadKey(publicKeyFilePath, out publicKey, out readKeyExeption))
        {
            exeptionString = readKeyExeption;
            return false;
        }

        try
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(publicKey);
            encryptedData = rsa.Encrypt(Encoding.UTF8.GetBytes(data), true);
        }
        catch (CryptographicUnexpectedOperationException ex)
        {
            exeptionString = ex.Message;
            return false;
        }
        catch (CryptographicException ex)
        {
            exeptionString = ex.Message;
            return false;
        }
        catch (Exception ex)
        {
            exeptionString = ex.Message;
            return false;
        }
        return true;
    }
}

